package com.cainaer.common.core.airecognition;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.cainaer.common.core.airecognition.domain.BusinessLicense;
import com.cainaer.common.core.airecognition.domain.IdCard;
import com.cainaer.common.core.airecognition.utils.*;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.HttpURLConnection;

/**
 * @author-> tina
 * @date-> 2020/9/1 下午3:18
 * @version-> 1.0
 * @description-> 百度 api 调用
 **/
public class Sample {
    /**
     * 设置APPID/AK/SK
     * 识别营业执照
     * 识别银行卡
     */
    private static final String APP_ID = "22557246";
    private static final String API_KEY = "GgqFjfdxXsau8qOX0miLXOH3";
    private static final String SECRET_KEY = "rQV8s0qym467GfN3teNdFH4W3zGZIlxI";
    private static final String BUSINESS_LICENSE_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license";
    private static final String BANK_CARD_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard";
    private static final String AUTH_HOST="https://aip.baidubce.com/oauth/2.0/token?";


    /**
     * 获取权限token
     *
     * @return 返回示例：
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     * // 官网获取的 API Key 更新为你注册的
     * // 官网获取的 Secret Key 更新为你注册的
     */
    public static String getAuth() {

        return getAuth(API_KEY, SECRET_KEY);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String getAccessTokenUrl = AUTH_HOST
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    /**
     * 初始化一个AipOcr
     *
     * @return
     */
    private static AipOcr initAip() {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        return client;
    }

    /**
     * 传入可选参数调用接口
     *
     * @return
     */
    public static HashMap<String, String> options() {
        HashMap<String, String> options = new HashMap<String, String>();
        // 是否检测朝向
        options.put("detect_direction", "false");
        // 是否检测风险
        options.put("detect_risk", "false");
        return options;
    }


    /**
     * 正反面front /back
     * 正面识别 身份证
     * idCard.put("name", words_result.getJSONObject("姓名").get("words"));
     * idCard.put("nation", words_result.getJSONObject("民族").get("words"));
     * idCard.put("address", words_result.getJSONObject("住址").get("words"));
     * idCard.put("sex", words_result.getJSONObject("性别").get("words"));
     * idCard.put("birth", words_result.getJSONObject("出生").get("words"));
     * idCard.put("number", words_result.getJSONObject("公民身份号码").get("words"));
     * return idCard.toString(2);
     *
     * @param photoPath
     * @return
     */
    public static IdCard front(String photoPath) {
        String idCardSide = "front";

        // 参数为本地图片路径
        try {
            JSONObject res = initAip().idcard(photoPath, idCardSide, options());
            System.out.println(res.toString(2));
            if (res != null) {
                IdCard idCard = new IdCard();
                JSONObject words_result = res.getJSONObject("words_result");
                if (com.cainaer.common.core.utils.StringUtils.equals("无", words_result.getJSONObject("姓名").getString("words")) ||
                        com.cainaer.common.core.utils.StringUtils.equals("无", words_result.getJSONObject("公民身份号码").getString("words"))) {
                    return null;
                }

                idCard.setSex((String) words_result.getJSONObject("性别").get("words"));
                idCard.setAddress((String) words_result.getJSONObject("住址").get("words"));
                idCard.setName((String) words_result.getJSONObject("姓名").get("words"));
                idCard.setNation((String) words_result.getJSONObject("民族").get("words"));
                idCard.setBirth((String) words_result.getJSONObject("出生").get("words"));
                idCard.setNumber((String) words_result.getJSONObject("公民身份号码").get("words"));

                return idCard;

            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 正反面front /back
     * 反面识别 身份证
     * idCard.put("expirationDate", words_result.getJSONObject("失效日期").get("words"));
     * idCard.put("issuingAuthority", words_result.getJSONObject("签发机关").get("words"));
     * idCard.put("dateOfIssue", words_result.getJSONObject("签发日期").get("words"));
     *
     * @param photoPath
     * @return
     */
    public static IdCard back(String photoPath) {

        String idCardSide = "back";

        // 参数为本地图片路径
        try {
            JSONObject res = initAip().idcard(photoPath, idCardSide, options());
            System.out.println(res.toString(2));
            if (res != null) {
                JSONObject words_result = res.getJSONObject("words_result");
                IdCard card = new IdCard();
                card.setExpirationDate((String) words_result.getJSONObject("失效日期").get("words"));
                card.setIssuingAuthority((String) words_result.getJSONObject("签发机关").get("words"));
                card.setDateOfIssue((String) words_result.getJSONObject("签发日期").get("words"));

                return card;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     * <p>
     * 银行卡识别
     */
    public static String bankCard(String filePath) {
        try {
            // 本地文件路径
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth(API_KEY, SECRET_KEY);
            String result = HttpUtil.post(BANK_CARD_URL, accessToken, param);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     * <p>
     * 营业执照识别
     * <p>
     * 如果社会信用码无法识别那就判断识别，别问我为什么这样做，因为前端的人多
     */
    public static BusinessLicense businessLicense(String filePath) {
        try {
            // 本地文件路径
            byte[] imgData = com.cainaer.common.core.utils.file.FileUtils.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            String accessToken = getAuth();
            String result = HttpUtil.post(BUSINESS_LICENSE_URL, accessToken, param);
            com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
            com.alibaba.fastjson.JSONObject words_result = object.getJSONObject("words_result");
            if (com.cainaer.common.core.utils.StringUtils.equals("无", words_result.getJSONObject("社会信用代码").getString("words"))) {
                return null;
            }
            BusinessLicense businessLicense = new BusinessLicense();
            businessLicense.setUnitName(words_result.getJSONObject("单位名称").getString("words"));
            businessLicense.setUnitType(words_result.getJSONObject("类型").getString("words"));
            businessLicense.setLegalPerson(words_result.getJSONObject("法人").getString("words"));
            businessLicense.setAddress(words_result.getJSONObject("地址").getString("words"));
            businessLicense.setValidity(words_result.getJSONObject("有效期").getString("words"));
            businessLicense.setIdNumber(words_result.getJSONObject("证件编号").getString("words"));
            businessLicense.setCode(words_result.getJSONObject("社会信用代码").getString("words"));
            businessLicense.setBusinessScope(words_result.getJSONObject("经营范围").getString("words"));
            businessLicense.setLayout(words_result.getJSONObject("组成形式").getString("words"));
            businessLicense.setCompanyCreateDate(words_result.getJSONObject("成立日期").getString("words"));
            businessLicense.setRegisteredCapital(words_result.getJSONObject("注册资本").getString("words"));
            return businessLicense;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
